package DualRMI;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class Server implements ConnectionListener {
	private int port;
	private String address;
	private Registry registry;
	private RemoteInterface serverRIObject;
	private RemoteInterface clientRIObject;
	
	public Server(int port){
		this.port = port;
		this.address = getInetAddress();
		serverRIObject = initializeRI("serverObj");
		setUpServer();
	}
	
	public int getPort(){
		return port;
	}
	
	private void setUpServer(){
		try {
			createRegistryAndBindRIObject();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void createRegistryAndBindRIObject() throws RemoteException, IOException {
		registry = LocateRegistry.createRegistry(port);
		System.out.println("Registry found");

		RemoteInterface stub = (RemoteInterface) UnicastRemoteObject.exportObject(serverRIObject, port);
		registry.rebind(serverRIObject.myId(), stub);
		System.out.println("Binded an object inside registry");
		System.out.println("Now we are waiting for a client");
	}
	
	private String getInetAddress(){
		try {
			return InetAddress.getLocalHost().toString();
		} catch (UnknownHostException e) {
			return null;
		}
	}
	
	private RemoteInterface initializeRI(String id){
		return new RemoteObject(id, this);
	}

	@Override
	public void event(ConnectionEvent event) {
		System.out.println("Event was triggered");
		if (event.type.equals("c")) {
			try {
				System.out.println("Trying to bound clientRIOject");
				
				clientRIObject = RemoteObject.lookupRIObject(event.id, registry);
				
				System.out.println("Bound clientRIObject");
				clientRIObject.print("yeah baby");
			} catch (RemoteException e) {
				System.out.println("Could not lookup the remote interface object in event");
				e.printStackTrace();
			}
		}
		
	}
}
